//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.ScientificWorkflow.UIDesigner
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Xml.Serialization;
    using Microsoft.Research.ScientificWorkflow.TridentUtilities;

    /// <summary>
    /// Logic for serialization and deserializing the supported output types object.
    /// </summary>
    public static class OutputSupportedTypesettingService
    {
        /// <summary>
        /// Output supported types.
        /// </summary>
        private static OutputSupportedTypes currentOutputSupportedTypes;

        /// <summary>
        /// Gets the supported types.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public static Collection<OutputType> GetSupportedTypes(string type)
        {
            Collection<OutputType> currentSupportedTypes = new Collection<OutputType>();

            if (currentOutputSupportedTypes == null)
            {
                currentOutputSupportedTypes = OutputSupportedTypesettingService.DeSerializeSettings(
                    UIDesignerCodeConstants.OUTPUTSUPPORTEDTYPESSETTINGSXMLPATH);
            }

            TypeMap currentMap = GetTypeMap(type);

            if (currentMap == null)
            {
                currentSupportedTypes.Add(new OutputType { Name = "text/plain" });
                currentSupportedTypes.Add(new OutputType { Name = "text/html" });
            }
            else
            {
                foreach (string category in currentMap.SupportedCategory)
                {
                    GetSupportedCategories(category, currentSupportedTypes);
                }
            }

            return currentSupportedTypes;
        }

        /// <summary>
        /// Gets the supported categories.
        /// </summary>
        /// <param name="category">The category.</param>
        /// <param name="currentSupportedTypes">The current supported types.</param>
        private static void GetSupportedCategories(string category, Collection<OutputType> currentSupportedTypes)
        {
            foreach (SystemType type in currentOutputSupportedTypes.SystemTypes)
            {
                if (type.TypeName.Equals(category))
                {
                    foreach (OutputType outputType in type.OutputTypes)
                    {
                        currentSupportedTypes.Add(outputType);
                    }
                }
            }
        }

        /// <summary>
        /// Gets the type map.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="currentMap">The current map.</param>
        /// <returns></returns>
        private static TypeMap GetTypeMap(string type)
        {
            TypeMap currentMap = null;
            foreach (TypeMap map in currentOutputSupportedTypes.TypeMaps)
            {
                if (map.TypeName.Equals(type))
                {
                    currentMap = map;
                    break;
                }
            }
            return currentMap;
        }

        /// <summary>
        /// Serialize the supported settings file.
        /// </summary>
        private static void SerializeSettings(OutputSupportedTypes supportedTypes, string xmlPath)
        {
            try
            {
                // Create the trident folder in user directory if it doesnt exist.
                string dirName = Path.GetDirectoryName(xmlPath);
                if (!string.IsNullOrEmpty(dirName) && !Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }

                // Delete existing file.
                if (File.Exists(xmlPath))
                {
                    File.Delete(xmlPath);
                }

                // Serialize to file.
                using (FileStream fileStream = new FileStream(xmlPath, FileMode.OpenOrCreate))
                {
                    XmlSerializer serializer = new XmlSerializer(supportedTypes.GetType());
                    serializer.Serialize(fileStream, supportedTypes);
                }
            }
            catch (IOException ex)
            {
                TridentErrorHandler.HandleAndThrowBusinessLogicException(ex,
                    TridentErrorConstants.ErrorNumber90000026,
                    ex.Message);
            }
            catch (UnauthorizedAccessException ex)
            {
                TridentErrorHandler.HandleAndThrowBusinessLogicException(ex,
                    TridentErrorConstants.ErrorNumber90000026,
                    ex.Message);
            }
        }

        /// <summary>
        /// Deserialize the supported settings file.
        /// </summary>
        private static OutputSupportedTypes DeSerializeSettings(string xmlPath)
        {
            OutputSupportedTypes supportedTypes = null;
            if (File.Exists(xmlPath))
            {
                try
                {
                    using (FileStream fileStream = new FileStream(xmlPath, FileMode.Open))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(OutputSupportedTypes));
                        object settingsObj = serializer.Deserialize(fileStream);
                        if (xmlPath != null)
                        {
                            supportedTypes = settingsObj as OutputSupportedTypes;
                        }
                    }
                }
                catch (IOException)
                {
                    // Ignore. load defaults.
                }
                catch (UnauthorizedAccessException)
                {
                    // Ignore. load defaults.
                }
                catch (InvalidOperationException)
                {
                    // Ignore. load defaults.
                }
            }
            if (supportedTypes == null)
            {
                supportedTypes = DefaultSettings();
            }

            return supportedTypes;
        }

        /// <summary>
        /// Get Default settings.
        /// </summary>
        /// <returns></returns>
        private static OutputSupportedTypes DefaultSettings()
        {
            SystemType stringType = new SystemType
            {
                TypeName = "StringType",
                OutputTypes = new Collection<OutputType>{
                new OutputType{ Name="text/plain"},
                new OutputType{ Name="text/html"}}
            };

            SystemType ImageType = new SystemType
            {
                TypeName = "ImageType",
                OutputTypes = new Collection<OutputType>{
                new OutputType{ Name="image/gif"},
                new OutputType{ Name="image/jpg"},
                new OutputType{ Name="image/bmp"},
                new OutputType{ Name="image/png"}}
            };

            SystemType byteArrayType = new SystemType
            {
                TypeName = "ByteArrayType",
                OutputTypes = new Collection<OutputType>{
                new OutputType{ Name="application/ms-excel"},
                new OutputType{ Name="application/ms-word"},
                new OutputType{ Name="application/xml"},
                new OutputType{ Name="application/csv"}}
            };


            SystemType allType = new SystemType
            {
                TypeName = "all",
                OutputTypes = new Collection<OutputType>{
                new OutputType{ Name="text/plain"},
                new OutputType{ Name="text/html"},
                new OutputType{ Name="image/gif"},
                new OutputType{ Name="image/jpg"},
                new OutputType{ Name="image/bmp"},
                new OutputType{ Name="image/png"},
                new OutputType{ Name="application/ms-excel"},
                new OutputType{ Name="application/ms-word"},
                new OutputType{ Name="application/xml"},
                new OutputType{ Name="application/csv"}}
            };


            SystemType objectType = new SystemType
            {
                TypeName = "ObjectType",
                OutputTypes = new Collection<OutputType>{
                new OutputType{ Name="text/plain"},
                new OutputType{ Name="text/html"}}
            };

            TypeMap stringMap = new TypeMap
            {
                TypeName = "System.string",
                SupportedCategory = new Collection<string>{
                    "StringType"}
            };

            TypeMap ImageMap = new TypeMap
            {
                TypeName = "System.Drawing.Image",
                SupportedCategory = new Collection<string>{
                    "ImageType"}
            };

            TypeMap ByteArrayMap = new TypeMap
            {
                TypeName = "System.Byte[]",
                SupportedCategory = new Collection<string>{
                    "ByteArrayType"}
            };

            TypeMap objectMap = new TypeMap
            {
                TypeName = "System.object",
                SupportedCategory = new Collection<string>{
                    "ObjectType"}
            };

            Collection<SystemType> types = new Collection<SystemType>{
                    stringType,
                    ImageType,
                    byteArrayType,
                    objectType,
                    allType};

            Collection<TypeMap> maps = new Collection<TypeMap>
            {
                stringMap,
                ImageMap,
                ByteArrayMap,
                objectMap
            };

            OutputSupportedTypes supportedType = new OutputSupportedTypes
            {
                SystemTypes = types,
                TypeMaps = maps
            };

            return supportedType;
        }
    }
}
